<template>
  <div style="width: 100%;height: 78vh;">
    <div>
      <h3>溯源管理</h3>
    </div>
    <div>
    </div>
    <!-- 增加\删除按钮 -->
    <div style="margin: 20px 0;">
      <el-button type="primary" @click="dialogOn">
        <el-icon class="el-iconss">
          <Plus />
        </el-icon>
        新增
      </el-button>
      <el-button type="primary" @click="Deletes()">
        <el-icon class="el-iconss">
          <Hide />
        </el-icon>
        删除
      </el-button>
      <div style="float: right;">
        <!-- 右侧按钮 -->
        <!-- 刷新 -->
        <el-icon class="el-icona">
          <RefreshRight />
        </el-icon>
        <!-- 设置 -->
        <el-icon class="el-icona">
          <Setting />
        </el-icon>
        <!-- 更多 -->
        <el-icon class="el-icona">
          <More />
        </el-icon>
      </div>
    </div>
    <!-- 显示列表 -->
    <div>
      <el-table :data="tableData" border row-key="traceaId" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="traceaId" label="序号" align="center" width="70">
          <template #default="{ row, index }">
            <!-- 判断是否是第一行，第一行显示输入框，其他行显示数据 -->
            <input v-if="index === 0" v-model="searchParams.traceaId" placeholder="输入进行查询">
            <span v-else>{{ row.traceaId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" align="center" width="120">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.goodsName" placeholder="输入进行查询">
            <span v-else>{{ row.goodsName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaBatch" label="生产批次" align="center" width="200">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaBatch" placeholder="输入进行查询">
            <span v-else>{{ row.traceaBatch }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaQualityDay" label="保质期(天)" align="center" width="120">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaQualityDay" placeholder="输入进行查询">
            <span v-else>{{ row.traceaQualityDay }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaLicenseCode" label="生产许可号" align="center" width="200">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaLicenseCode" placeholder="输入进行查询">
            <span v-else>{{ row.traceaLicenseCode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaEnterpriseName" label="生产企业" align="center" width="200">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaEnterpriseName" placeholder="输入进行查询">
            <span v-else>{{ row.traceaEnterpriseName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaImprove" label="信息完善度" align="center" width="100">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaImprove" placeholder="输入进行查询">
            <span v-else>{{ row.traceaImprove }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaCreateName" label="创建人" align="center" width="100">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaCreateName" placeholder="输入进行查询">
            <span v-else>{{ row.traceaCreateName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaCreateTime" label="创建时间" align="center" width="180">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaCreateTime" placeholder="输入进行查询">
            <span v-else>{{ row.traceaCreateTime ? moment(row.traceaCreateTime).format("yyyy-MM-DD HH:mm:ss") : "空"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="traceaUpdateName" label="修改人" align="center" width="100">
          <template #default="{ row, index }">
            <input v-if="index === 0" v-model="searchParams.traceaUpdateName" placeholder="输入进行查询">
            <span v-else>{{ row.traceaUpdateName ? moment(row.traceaUpdateName).format("yyyy-MM-DD HH:mm:ss") : "空"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" min-width="155">
          <template v-slot="scoped">
            <el-button link type="primary" size="small" @click="intraceability(scoped.row)" v-show="true">详情</el-button>
            <el-button link type="primary" size="small" @click="Update(scoped.row)" v-show="true">修改</el-button>
            <el-button link type="primary" size="small" @click="Deletes(scoped.row.traceaBatch)"
              v-show="true">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- {{ tableData }} -->
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="page.TotalIndex" v-model:page-size="page.TotalSize"
        :page-sizes="[1, 5, 10, 15, 20, 25, 30]" background="background"
        layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount" />
    </div>
  </div>
  <!-- 添加对话框 -->
  <div>
    <el-dialog v-model="dialogFormVisible" title="基本信息" width="500" draggable="true">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="Addform" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="商品名称" prop="goodsName">
          <el-select v-model="Addform.goodsName" placeholder="请选择商品名称" clearable>
            <el-option label="兔头(麻辣味)" value="兔头(麻辣味)" />
            <el-option label="兔头(孜然味)" value="兔头(孜然味)" />
            <el-option label="兔腿(麻辣味)" value="兔腿(麻辣味)" />
            <el-option label="兔腿(孜然味)" value="兔腿(孜然味)" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="traceaBatch">
          <el-input v-model="Addform.traceaBatch" show-word-limit maxlength="30" />
        </el-form-item>
        <el-form-item label="保质期(天)" prop="traceaQualityDay">
          <el-input v-model="Addform.traceaQualityDay" show-word-limit maxlength="5" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="traceaLicenseCode">
          <el-input v-model="Addform.traceaLicenseCode" />
        </el-form-item>
        <el-form-item label="生产企业" prop="traceaEnterpriseName">
          <el-input v-model="Addform.traceaEnterpriseName" />
        </el-form-item>
        <el-form-item label="封面图" prop="traceaPicture">
          <el-upload class="avatar-uploader" action="https://localhost:7281/api/UploadTuPian" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
  <!-- 修改对话框 -->
  <div>
    <el-dialog v-model="dialogFormVisibleupdate" title="基本信息" width="500" draggable="true">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="Addform" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="商品名称" prop="goodsName">
          <el-select v-model="Addform.goodsName" placeholder="请选择商品名称" clearable>
            <el-option label="兔头(麻辣味)" value="兔头(麻辣味)" />
            <el-option label="兔头(孜然味)" value="兔头(孜然味)" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="traceaBatch">
          <el-input v-model="Addform.traceaBatch" show-word-limit maxlength="30" />
        </el-form-item>
        <el-form-item label="保质期(天)" prop="traceaQualityDay">
          <el-input v-model="Addform.traceaQualityDay" show-word-limit maxlength="5" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="traceaLicenseCode">
          <el-input v-model="Addform.traceaLicenseCode" />
        </el-form-item>
        <el-form-item label="生产企业" prop="traceaEnterpriseName">
          <el-input v-model="Addform.traceaEnterpriseName" />
        </el-form-item>
        <el-form-item label="封面图" prop="traceaPicture">
          <el-upload class="avatar-uploader" action="https://localhost:7281/api/UploadTuPian" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatass(ruleFormRef)">
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { compile, computed, onMounted, reactive, ref, watch } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();

//#region 详情跳转
const intraceability = (row: any) => {
  //溯源信息pinia存值
  store.ccTrace.goodsName = row.goodsName
  store.ccTrace.traceaBatch = row.traceaBatch
  store.ccTrace.traceaQualityDay = row.traceaQualityDay
  store.ccTrace.traceaLicenseCode = row.traceaLicenseCode
  store.ccTrace.traceaEnterpriseName = row.traceaEnterpriseName
  store.ccTrace.traceaPicture = row.traceaPicture

  router.push({
    name: 'InTraceability',
    query: row
  })
}



//#endregion

//#region 添加

const dialogFormVisible = ref(false) //对话框开关
const formLabelWidth = '140px'

const ruleFormRef = ref<FormInstance>()
const formSize = ref<ComponentSize>('default')
//效验
const rules = reactive<FormRules>({
  goodsName: [
    { required: true, message: '必填项', trigger: 'blur' },
  ],
  traceaBatch: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 0, max: 30, message: '最多支持输入 30 位字符', trigger: 'blur' },
  ],
  traceaQualityDay: [
    { required: true, message: '必填项', trigger: 'blur' },
    // { min: 0, max: 5, message: '最多支持输入 5 位字符', trigger: 'blur' },
    {
      pattern: /^\d+$/, message: '请输入数字', trigger: 'blur'
    }
  ],
  traceaLicenseCode: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 0, max: 30, message: '最多支持输入 30 位字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]+$/, message: '只允许输入数字、字母（包括大写、小写）', trigger: 'blur'
    }
  ],
  traceaEnterpriseName: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 0, max: 30, message: '最多支持输入 30 位字符', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur'
    }
  ],
  traceaPicture: [
    { required: true, message: '必填项', trigger: 'blur' },
  ],
})

//打开对话框
const dialogOn = () => {
  //清空操作
  Addform.goodsName = '';
  Addform.traceaBatch = `ZS${Math.floor(Date.now() / 1)}`;
  Addform.traceaQualityDay = "";
  Addform.traceaLicenseCode = `SC${Math.floor(Date.now() / 1000)}`;
  Addform.traceaEnterpriseName = '';
  Addform.traceaImprove = 0;
  imageUrl.value = ""
  dialogFormVisible.value = true //打开对话框
}


//添加对象
const Addform = reactive({
  traceaId: null,
  "goodsName": "",          //商品名称
  "traceaBatch": "",          //生产批次
  "traceaQualityDay": '',      //保质期(天)
  "traceaLicenseCode": "",    //生产许可证号
  "traceaEnterpriseName": "", //生产企业
  "traceaImprove": 0,         //完成度
  "traceaCreateName": store.ccstore.nickName,     //创建人
  "traceaCreateTime": new Date(),//创建时间
  "traceaUpdateName": "",     //修改人
  "traceaUpdateTime": null,     //修改时间
  "traceaPicture": "",        //封面图
  "traceaIsNo": false,        //隐藏
  "traceaIsDelete": false     //逻辑删
})

//添加
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post('https://localhost:7281/api/Trace/AddTraceModel', Addform).then(res => {
        if (res.data.code === 219) {
          //重复
          ElMessage.error(res.data.msg)
        } else if (res.data.code === 212) {
          //添加成功
          ElMessage.success(res.data.msg)
        } else {
          //添加失败
          ElMessage.error(res.data.msg)
        }
        dialogFormVisible.value = false //关闭对话框
        show();
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//图片添加操作
//定义图片存放变量
const imageUrl = ref('')

//上传后获取数据url
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  imageUrl.value = response.imgss;
  console.log(response, '返回的图片数据')
  console.log(imageUrl.value, "上传图片获取路径")
  Addform.traceaPicture = imageUrl.value
}

//图片上传前操作
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('只允许image/jpeg格式')
  //   return false
  // }
  // else if (rawFile.size / 1024 / 1024 > 2) {
  //   ElMessage.error('Avatar picture size can not exceed 2MB!')
  //   return false
  // }
  return true
}




//#endregion


//#region 溯源管理页面显示
//条件查询
const searchParams = reactive({
  traceaId: '',
  goodsName: '',
  traceaBatch: '',
  traceaQualityDay: '',
  traceaLicenseCode: '',
  traceaEnterpriseName: '',
  traceaImprove: '',
  traceaCreateName: '',
  traceaCreateTime: '',
  traceaUpdateName: ''
})

//分页
const page = reactive({
  TotalIndex: 1,
  TotalSize: 15,
  totalCount: 0,
  totalPage: 0,
})

//存储请假申请表数据集合
const tableData = ref([])
//获取集合数据
const show = () => {
  axios.get("https://localhost:7070/api/Trace/ListTracea", {
    params: {
      ToIndex: page.TotalIndex,
      ToSize: page.TotalSize
    }
  }).then(res => {
    tableData.value = res.data.items
    page.totalCount = res.data.totalCount
    page.totalPage = res.data.totalPage
    console.log(res.data, "显示数据")
  })
}

onMounted(() => {
  show();
})

watch(page, () => { show(); })

//#endregion

//#region 多选--生产批次
const multipleSelection = ref([])

const handleSelectionChange = (date: any) => {
  multipleSelection.value = date.map((x: any) => x.traceaBatch)
  console.log(multipleSelection.value, "选中多选")
}

//#endregion

//#region 删除多选
//删除(逻辑删除)
const Deletes = (traceaBatch?: string) => {

  let traceaBatchArray: string[] = [];
  if (traceaBatch) {
    //单个删除
    traceaBatchArray = [traceaBatch];
  } else if (multipleSelection.value.length > 0) {
    //多选删除
    traceaBatchArray = multipleSelection.value
  } else {
    ElMessage.warning('请选择要删除的数据');
    return;
  }

  console.log(multipleSelection.value, "删除执行编号")
  axios.delete('https://localhost:7281/api/Trace/DeleteTrace', {
    data: { traceaBatch: traceaBatchArray }
  }).then(res => {
    if (res.data.code == 205) {
      // 删除失败
      ElMessage.error(res.data.msg)
    } else {
      // 删除成功
      ElMessage.success(res.data.msg)
      show();
    }
  })
}

//#endregion

//#region 修改

//打开修改对话框
const dialogFormVisibleupdate = ref(false)
//修改
const Update = (row: any) => {
  dialogFormVisibleupdate.value = true //打开修改对话框

  console.log(row, "修改数据")
  //修改数据
  Addform.traceaId = row.traceaId;
  Addform.goodsName = row.goodsName;
  Addform.traceaBatch = row.traceaBatch;
  Addform.traceaQualityDay = row.traceaQualityDay;
  Addform.traceaLicenseCode = row.traceaLicenseCode;
  Addform.traceaEnterpriseName = row.traceaEnterpriseName;
  Addform.traceaUpdateName = row.traceaUpdateName;
  // Addform.traceaUpdateTime = new Date(),
  Addform.traceaPicture = row.traceaPicture;
  imageUrl.value = row.traceaPicture;
}

//修改
const updatass = async (formEl: FormInstance | undefined) => {
  console.log(Addform.traceaQualityDay, "修改保质期天数")
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //修改请求
      axios.put(`https://localhost:7281/api/Trace/UpdateTrace`, Addform).then(res => {
        if (res.data.code == 206) {
          //修改成功
          ElMessage.success(res.data.msg)
          dialogFormVisibleupdate.value = false //关闭修改对话框
          show();
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//#endregion

onMounted(() => {
  show();
})

</script>

<style scoped>
.el-iconss {
  font-size: 15px;
}

.el-icona {
  margin-right: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 50px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  text-align: center;
}
</style>
